﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IMeem.BO;
using IMeem.Commands;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace IMeem.ViewModels
{
    public class IMeemViewModel : INotifyPropertyChanged
    {
        public delegate void SearchAsyncStartedHandler(string keyword);
        public event SearchAsyncStartedHandler SearchAsyncStarted;
        private IMeem.API.IMeem _imeem;
        public NextResultsCommand NextResultsCmd { get; set; }
        public PreviousResultsCommand PreviousResultsCmd { get; set; }

        public ObservableCollection<SearchResult> _latestSearchResults;
        public ObservableCollection<SearchResult> LatestSearchResults 
        {
            get
            {
                return _latestSearchResults;
            }
        }

        public IMeemViewModel()
        {
            _imeem = new IMeem.API.IMeem();
            _imeem.SearchAsyncStarted += new IMeem.API.IMeem.SearchAsyncStartedHandler(_imeem_SearchAsyncStarted);
            _latestSearchResults = new ObservableCollection<SearchResult>();
            NextResultsCmd = new NextResultsCommand(this);
            PreviousResultsCmd = new PreviousResultsCommand(this);
            _imeem.SearchAsyncCompleted += new IMeem.API.IMeem.SearchAsyncCompletedHandler(_imeem_SearchAsyncCompleted);
        }

        void _imeem_SearchAsyncStarted(string keyword)
        {
            if (SearchAsyncStarted != null)
                SearchAsyncStarted(keyword);
        }

        void _imeem_SearchAsyncCompleted(List<SearchResult> results)
        {
            _latestSearchResults = new ObservableCollection<SearchResult>(results);
            RaisePropertyChanged("LatestSearchResults");
        }

        public void SearchAsync(string keyword, bool isNewSearch)
        {
            _imeem.SearchAsync(keyword, isNewSearch);
        }

        public void NextResults()
        {
            _imeem.NextResults();
        }

        public void PreviousResults()
        {
            _imeem.PreviousResults();
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}
